package cn.tedu.sp11zuul.filter;

import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class AccessFilter extends ZuulFilter {
    //设置过滤器类型  pre  routing   post  error
    @Override
    public String filterType() {
        //return "pre";
        return FilterConstants.PRE_TYPE;
    }
    //设置过滤器添加的位置顺序号
    //在默认过滤器的第5个过滤器中，在上下文对象中添加了serviceId
    @Override
    public int filterOrder() {
        return 6;
    }
        //判断对当前请求，是否要执行过滤代码
    @Override
    public boolean shouldFilter() {
        /**
         * 如果调用商品必须登录才能调用；调用其他服务可以任意执行
         */
        //得到当前请求的后台服务id
        RequestContext ctx = RequestContext.getCurrentContext();
        String serviceId=(String)ctx.get(FilterConstants.SERVICE_ID_KEY);//"serviceId"
        //判断服务id是否是“item-service
        return "item-service".equalsIgnoreCase(serviceId);
    }

    @Override
    public Object run() throws ZuulException {
        //得到request对象
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request =
                ctx.getRequest();

        //接收token参数
        String token = request.getParameter("token");
        //如果没有token
        if(StringUtils.isBlank(token)){
            //1.阻止继续执行
            ctx.setSendZuulResponse(false);
            //2.向客户端返回响应“没有登录”
            String json = JsonResult.err().code(JsonResult.NOT_LOGIN).msg("没有登录").toString();
            ctx.addZuulResponseHeader("Content-type", "application/json;charset=UTF-8");
            ctx.setResponseBody(json);
        }


        return null;
    }
}
